<?php
namespace model;
require_once __DIR__.'/../utils/MysqlDBUtils.php';
use utils\MysqlDBUtils;


class BookModel {
    private $dbUtil;

    // 构造函数
    public function __construct() {
        $this->dbUtil = new MysqlDBUtils(); // 初始化数据库工具类
    }

    public function getAllBooks() {
        $sql = "SELECT * FROM book";
        return $this->dbUtil->prepareQuery($sql); // 使用dbUtil执行查询
    }

    // 获取带分页和搜索的图书列表
    public function getPaginatedBooks($q = '', $currentPage = 1, $perPage = 8) {
        // 处理搜索条件
        $whereCondition = '';
        if (!empty($q)) {
            $qLike = "%{$q}%";
            $whereCondition = "WHERE title LIKE '$qLike' OR isbn LIKE '$qLike' OR author LIKE '$qLike'";
        }

        // 查询总记录数
        $totalSql = "SELECT COUNT(*) AS total FROM book {$whereCondition}";
        $totalResult = $this->dbUtil->prepareQuery($totalSql);
        $total = $totalResult ? $totalResult[0]['total'] : 0;

        // 计算分页偏移量
        $offset = ($currentPage - 1) * $perPage;
        $sql = "SELECT * FROM book {$whereCondition} LIMIT $offset, $perPage";
        $books = $this->dbUtil->prepareQuery($sql);

        // 返回分页数据
        return [
            'books' => $books,
            'total' => $total,
            'currentPage' => $currentPage,
            'perPage' => $perPage,
            'totalPages' => max(1, ceil($total / $perPage))
        ];
    }

}
?>

